'''
Created on Sep 18, 2009

@author: mkiyer
'''
import logging


class ParseError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)

def simple_bed_reader(fhd):
    for linenum, line in enumerate(fhd):
        line = line.strip()
        if line is None:
            continue
        if line.startswith('#'):
            logging.debug("skipping comment line %d: %s" % (linenum, line))
            continue
        fields = line.split('\t')
        if not fields[0].startswith('chr'):
            fields[0] = 'chr%s' % fields[0]
        yield (fields[0], int(fields[1]), int(fields[2]))
        

def str2list(s):
    fields = s.split(',')
    result = []
    for f in fields:
        if f:
            result.append(int(f))
    return result
    
_bed_fields = [('chrom', None), 
               ('start', int),
               ('end', int),
               ('name', None),
               ('score', float),
               ('strand', None),
               ('thickStart', int), 
               ('thickEnd', int),
               ('itemRgb', None),
               ('blockCount', int), 
               ('blockSizes', str2list),
               ('blockStarts', str2list)]

class BEDAnnotation(object):
    def __init__(self):
        self.is_track_line=False        
    @property
    def name(self):
        return self._name if hasattr(self, '_name') else None
    @property
    def score(self):
        return self._score if hasattr(self, '_score') else None
    @property
    def strand(self):
        return self._strand if hasattr(self, '_strand') else None
    @property
    def thickStart(self):
        return self._thickStart if hasattr(self, '_thickStart') else None
    @property
    def thickEnd(self):
        return self._thickEnd if hasattr(self, '_thickEnd') else None
    @property
    def blockCount(self):
        return self._blockCount if hasattr(self, '_blockCount') else None
    @property
    def blockSizes(self):
        return self._blockSizes if hasattr(self, '_blockSizes') else None
    @property
    def blockStarts(self):
        return self._blockStarts if hasattr(self, '_blockStarts') else None

    def __str__(self):
        # required fields
        #allfields = ['%s:%d-%d' % (self.chrom, self.start, self.end)]
        allfields = [self.chrom, str(self.start), str(self.end)]
        optfields = ['.'] * len(_bed_fields[3:])
        maxfield = -1
        for i, field in enumerate(_bed_fields[3:]):
            field_attr = '_' + field[0]
            if hasattr(self, field_attr):
                optfields[i] = str(getattr(self, field_attr))
                maxfield = i
        # combine required and optional fields
        allfields.extend(optfields[:(maxfield+1)])
        return '\t'.join(allfields)    
    

def bed_reader(fhd, track_lines=False, cols=None):
    '''
    From http://genome.ucsc.edu/FAQ/FAQformat#format1:
    
    BED format provides a flexible way to define the data lines that are displayed in an annotation track. 
    
    BED lines have three required fields and nine additional optional fields. The number of fields per line 
    must be consistent throughout any single set of data in an annotation track. 
    
    The order of the optional fields is binding: lower-numbered fields must always be populated if 
    higher-numbered fields are used.

    The first three required BED fields are:
    1. chrom - The name of the chromosome (e.g. chr3, chrY, chr2_random) or scaffold (e.g. scaffold10671).    
    2. chromStart - The starting position of the feature in the chromosome or scaffold. The first base in a chromosome is numbered 0.
    3. chromEnd - The ending position of the feature in the chromosome or scaffold. The chromEnd base is not included in the display of the feature. For example, the first 100 bases of a chromosome are defined as chromStart=0, chromEnd=100, and span the bases numbered 0-99. 

    The 9 additional optional BED fields are:
    4. name - Defines the name of the BED line. This label is displayed to the left of the BED line in the Genome Browser window when the track is open to full display mode or directly to the left of the item in pack mode.
    5. score - A score between 0 and 1000. If the track line useScore attribute is set to 1 for this annotation data set, the score value will determine the level of gray in which this feature is displayed (higher numbers = darker gray).
    6. strand - Defines the strand - either '+' or '-'.
    7. thickStart - The starting position at which the feature is drawn thickly (for example, the start codon in gene displays).
    8. thickEnd - The ending position at which the feature is drawn thickly (for example, the stop codon in gene displays).
    9. itemRgb - An RGB value of the form R,G,B (e.g. 255,0,0). If the track line itemRgb attribute is set to "On", this RBG value will determine the display color of the data contained in this BED line. NOTE: It is recommended that a simple color scheme (eight colors or less) be used with this attribute to avoid overwhelming the color resources of the Genome Browser and your Internet browser.
    10. blockCount - The number of blocks (exons) in the BED line.
    11. blockSizes - A comma-separated list of the block sizes. The number of items in this list should correspond to blockCount.
    12. blockStarts - A comma-separated list of block starts. All of the blockStart positions should be calculated relative to chromStart. The number of items in this list should correspond to blockCount. 
    '''        
    linenum = 0
    for linenum, line in enumerate(fhd):
        if line is None:
            continue
        myline = line.strip()
        if myline.startswith('#'):
            logging.debug("skipping comment line %d: %s" % (linenum, myline))
            continue
        if myline.startswith('track'):
            logging.debug("found track header line %d: %s"  % (linenum, myline))
            if track_lines is True:
                annot = BEDAnnotation()
                annot.is_track_line = True
                annot.line = line
                yield annot
            continue
        thisfields = myline.split()
        # first three fields are required
        if len(thisfields) < 3:
            raise ParseError('error reading line: %s' % myline)
        annot = BEDAnnotation()
        for i in xrange(0, 3):
            field_name, field_func = _bed_fields[i]
            setattr(annot, field_name,
                    field_func(thisfields[i]) if field_func is not None else thisfields[i])
        
        if cols != None:
            last_col = min(cols, len(thisfields)) 
        
        for i in xrange(3, last_col):
            field_name, field_func = _bed_fields[i]
            setattr(annot, '_' + field_name,
                    field_func(thisfields[i]) if field_func is not None else thisfields[i])
        yield annot

